﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace AntUnion.FrameWork.Util
{
    public class ByteConvertUtil
    {
        ///<summary>
        /// 序列化
        /// </summary>
        /// <param name="data">要序列化的对象</param>
        /// <returns>返回存放序列化后的数据缓冲区</returns>
        public static byte[] Serialize(object data)
        {
            if (data == null)
                return null;
            XmlSerializer formatter = new XmlSerializer(data.GetType());
            MemoryStream rems = new MemoryStream();
            formatter.Serialize(rems, data);
            return rems.GetBuffer();
        }


        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data">数据缓冲区</param>
        /// <returns>对象</returns>
        public static object Deserialize<T>(byte[] data)
        {
            XmlSerializer formatter = new XmlSerializer(typeof(T));
            MemoryStream rems = new MemoryStream(data);
            return formatter.Deserialize(rems);
        }
    }
}
